﻿using System;
using System.Collections.Generic;
using Microsoft.Extensions.Hosting;
using SuperSocket.ProtoBase;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SuperSocket.Server.Abstractions;
using SuperSocket.Server.Host;


var builder = SuperSocketHostBuilder.Create<StringPackageInfo, CommandLinePipelineFilter>();

/******************************* 服务配置 *******************************/

// 编码配置>文件配置(如果删除编码配置,程序会从appsetting.json读取配置)
builder.ConfigureSuperSocket(opt => {
    opt.Name = "Default Server";
    
    //同时监听多个网卡(端口)
    opt.Listeners = new[] {
        new ListenOptions { Ip = "Any", Port = 6018 },
        new ListenOptions { Ip = "127.0.0.1", Port = 6019, NoDelay = true }
    }.ToList();
});


// 添加控制台日志
builder.ConfigureLogging((hostCtx, logger) => { logger.AddConsole(); });

/******************************* 处理会话 *******************************/

builder.UseSessionHandler((session) => {
        Console.WriteLine($"==> {session.RemoteEndPoint} 已连接");
        return session.SendAsync("[Server]已成功连接到服务器...\r\n\r\n"u8.ToArray());
    }, (session, reason) => {
        Console.WriteLine($"==> {session.RemoteEndPoint} 已断开,{reason}");
        return ValueTask.CompletedTask;
    });


/***************************** (路由)处理程序 ****************************/

builder.UsePackageHandler(async (session, package) =>
{
    // 原始写法
    // switch (package.Key.ToLower()) {
    //     case ("echo"):
    //         // 打印package信息
    //         var resp = string.Format($"[{package.Key}] Body={package.Body}  Parameters={string.Join(",", package.Parameters)} \r\n\r\n");
    //         await session.SendAsync(Encoding.UTF8.GetBytes(resp));
    //         break;
    //     default:
    //         await session.SendAsync("Bad Request"u8.ToArray());
    //         break; 
    // }
    
    // 简化写法 - 模拟不同的Command-Handler
    var response = package.Key.ToLower() switch
    {
        "echo" => string.Format($"[{package.Key}] Body={package.Body}  Parameters={string.Join(",",package.Parameters)}"),
        "1001" => string.Format($"[{package.Key}] 用户已登录({package.Body})"),
        "1002" => string.Format($"[{package.Key}] 用户已退出..."),
        _ => "Bad Request"
    };
    await session.SendAsync(Encoding.UTF8.GetBytes(response + "\r\n\r\n"));
});


var host = builder.Build();
await host.RunAsync();